package com.youlu.campus.wechat.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.RSAPublicKeyConfig;
import com.wechat.pay.java.service.profitsharing.ProfitsharingService;
import com.wechat.pay.java.service.profitsharing.model.AddReceiverRequest;
import com.wechat.pay.java.service.profitsharing.model.AddReceiverResponse;
import com.wechat.pay.java.service.profitsharing.model.DeleteReceiverRequest;
import com.wechat.pay.java.service.profitsharing.model.DeleteReceiverResponse;
import com.youlu.campus.common.exception.BusinessException;
import com.youlu.campus.entity.WechatMerchantConfig;
import com.youlu.campus.entity.wechat.enums.WechatMerchantConfigVerifyEnum;
import com.youlu.campus.service.wechat.WechatMerchantConfigService;
import com.youlu.campus.wechat.entity.SharingAccountInfo;
import com.youlu.campus.wechat.entity.WechatAppIdAccount;
import com.youlu.campus.wechat.entity.WechatProfitSharingLog;
import com.youlu.campus.wechat.service.SharingAccountInfoService;
import com.youlu.campus.wechat.service.WechatAppIdAccountService;
import com.youlu.campus.wechat.service.WechatProfitSharingLogService;
import com.youlu.campus.wechat.service.WechatProfitSharingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 微信分账 服务实现
 *
 * @Description: WechatBrandProfitSharingService
 * @Date 2025/10/23
 * @author: su
 */
@Slf4j
@Service
public class WechatProfitSharingServiceImpl implements WechatProfitSharingService {


    @Autowired
    private WechatMerchantConfigService wechatMerchantConfigService;

    @Autowired
    private SharingAccountInfoService sharingAccountInfoService;

    @Autowired
    private WechatProfitSharingLogService wechatBrandProfitSharingLogService;

    @Autowired
    private WechatAppIdAccountService wechatAppIdAccountService;


    private final Map<String, ProfitsharingService> serviceMap = new ConcurrentHashMap<>();

    private ProfitsharingService getService(WechatMerchantConfig wechatMerchantConfig) {
        return serviceMap.computeIfAbsent(wechatMerchantConfig.getMerchantId(), k -> {
            try {
                String privateKeyPath = wechatMerchantConfig.getPathPrivateKey(); // 商户 API 私钥路径
                String merchantSerialNumber = wechatMerchantConfig.getSerialNumber(); // 商户证书序列号
                String apiV3Key = wechatMerchantConfig.getApiV3Key(); // 商户 APIV3 密钥
                String merchantId = wechatMerchantConfig.getMerchantId();//商户号
                String pubPath = wechatMerchantConfig.getPathPublicKey();//公钥路径
                String publicKeyId = wechatMerchantConfig.getPublicKeyId();//公钥id

                Config config;
                if (WechatMerchantConfigVerifyEnum.PLATFORM_CERTIFICATE.getValue().equals(wechatMerchantConfig.getVerifyMode())) {
                    //平台证书认证
                    config = new RSAAutoCertificateConfig.Builder()
                            .merchantId(merchantId)
                            .privateKeyFromPath(privateKeyPath)
                            .merchantSerialNumber(merchantSerialNumber)
                            .apiV3Key(apiV3Key)
                            .build();

                } else {
                    //公钥模式认证
                    config = new RSAPublicKeyConfig.Builder()
                            .merchantId(merchantId)
                            .privateKeyFromPath(privateKeyPath)
                            .publicKeyFromPath(pubPath)
                            .publicKeyId(publicKeyId)
                            .merchantSerialNumber(merchantSerialNumber)
                            .apiV3Key(apiV3Key)
                            .build();
                }
                // 初始化服务
                return new ProfitsharingService.Builder().config(config).build();
            } catch (Exception e) {
                // 处理初始化异常，记录日志并抛出运行时异常或返回默认值
                throw new RuntimeException("Failed to initialize BrandProfitSharingService for merchant: " + wechatMerchantConfig.getMerchantId(), e);
            }
        });
    }

    @Override
    public AddReceiverResponse addReceiver(WechatProfitSharingLog param) {
        // 参数校验
        SharingAccountInfo accountInfo = sharingAccountInfoService.findById(param.getAccountId());
        if (accountInfo == null) {
            throw new BusinessException("分账账户信息获取失败");
        }
        WechatMerchantConfig merchantConfig = wechatMerchantConfigService.findByMerchantIdAndDecrypt(param.getMerchantId());
        if (merchantConfig == null) {
            throw new BusinessException("商户信息获取失败");
        }
        List<WechatAppIdAccount> wechatAppIdAccounts = wechatAppIdAccountService.listByMerchantId(merchantConfig.getMerchantId());
        WechatAppIdAccount wechatAppIdAccount;
        if (CollectionUtils.isEmpty(wechatAppIdAccounts)) {
            wechatAppIdAccount = wechatAppIdAccountService.findFirst();
        } else {
            wechatAppIdAccount = wechatAppIdAccounts.get(0);
        }
        try {
            ProfitsharingService service = getService(merchantConfig);
            AddReceiverRequest request = new AddReceiverRequest();
            request.setAppid(wechatAppIdAccount.getAppId());
            request.setAccount(accountInfo.getAccount());
            request.setName(accountInfo.getName());
            request.setSubAppid(accountInfo.getSubAppid());
            request.setName(accountInfo.getName());
            if (accountInfo.getRelationType() != null) {
                request.setRelationType(accountInfo.getRelationType());
            }
            if (accountInfo.getType() != null) {
                request.setType(accountInfo.getType());
            }
            // 记录请求日志（可选）
            log.info("addReceiver request:{}", JSONObject.toJSONString(request));
            AddReceiverResponse addReceiverResponse = service.addReceiver(request);
            log.info("addReceiver response:{}", JSONObject.toJSONString(addReceiverResponse));
            wechatBrandProfitSharingLogService.save(param);
            return addReceiverResponse;
        } catch (Exception e) {
            log.error("addReceiver error: {}", e.getMessage(), e);
            throw new BusinessException("添加分账信息失败");
        }
    }

    @Override
    public DeleteReceiverResponse deleteReceiver(WechatProfitSharingLog param) {
        // 参数校验
        SharingAccountInfo accountInfo = sharingAccountInfoService.findById(param.getAccountId());
        if (accountInfo == null) {
            throw new BusinessException("分账账户信息获取失败");
        }
        WechatMerchantConfig merchantConfig = wechatMerchantConfigService.findByMerchantIdAndDecrypt(param.getMerchantId());
        if (merchantConfig == null) {
            throw new BusinessException("商户信息获取失败");
        }
        try {
            ProfitsharingService service = getService(merchantConfig);

            DeleteReceiverRequest request = new DeleteReceiverRequest();
            request.setAccount(accountInfo.getAccount());
            request.setSubAppid(accountInfo.getSubAppid());
            if (accountInfo.getType() != null) {
                request.setType(accountInfo.getType());
            }
            // 记录请求日志（可选）
            log.info("deleteReceiver request:{}", JSONObject.toJSONString(request));
            DeleteReceiverResponse deleteReceiverResponse = service.deleteReceiver(request);
            log.info("deleteReceiver response:{}", JSONObject.toJSONString(deleteReceiverResponse));
            wechatBrandProfitSharingLogService.deleteByMerchantIdAndAccountId(param.getMerchantId(), param.getAccountId());
            return deleteReceiverResponse;
        } catch (Exception e) {
            log.error("deleteReceiver error: {}", e.getMessage(), e);
            throw new BusinessException("删除分账信息失败");
        }
    }
}
